package com.itheima.reggie.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
//公共属性填充管理器
//自定义元数据对象处理器
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
	//插入对象自动填充
	@Override
	public void insertFill(MetaObject metaObject) {
		metaObject.setValue("createTime", new Date());
		metaObject.setValue("updateTime", new Date());
		
		//如果当前用户在ThreadLocal中存在,则可以获取当前用户信息
		Employee employee = EmployeeHolder.get();
		
		if (employee != null) {
			metaObject.setValue("createUser", employee.getId());
			metaObject.setValue("upadteUser", employee.getId());
		}
		
		User user = UserHolder.getUser();
		if (user != null) {
			metaObject.setValue("createUser",user.getId());
			metaObject.setValue("updateUser",user.getId());
		}
	}
	
	//更新操作自动填充
	@Override
	public void updateFill(MetaObject metaObject) {
		metaObject.setValue("updateTime",new Date());
		Employee employee = EmployeeHolder.get();
		
		if (employee != null) {
			metaObject.setValue("updateUser",employee.getId());
		}
		
		User user = UserHolder.getUser();
		if (user != null) {
			metaObject.setValue("updateUser", user.getId());
		}
	}
	//插入操作自动填充
	
}
